<template>
  <div class="table-default">
    <el-button class="btn" type="primary" @click="goBack">返回</el-button>
    <el-button type="success" @click="submitForm(ruleFormRef, route.query.btnName)" v-loading.fullscreen.lock="fullscreenLoading">{{ route.query.btnName }}</el-button>

    <el-form :model="form" label-width="100px" :inline="true" :rules="rules" ref="ruleFormRef">
      <el-form-item>
        <!-- <el-radio-group v-model="radioValue" style="padding-left: 10px" @change="changeSelect"> -->
        <el-radio-group v-model="radioValue" style="padding-left: 10px">
          <el-radio label="1" border>单独方案</el-radio>
          <el-radio label="2" border>共用方案</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="物料编码" prop="productname" v-if="radioValue == '1'" @click="materielopen">
        <el-input v-model="curMaterielName" readonly />
        <!-- <el-input v-model="form.productname" style="opacity: 0.5" /> -->
        <!-- <el-select v-model="form.productname" style="width: 240px" allow-create filterable :reserve-keyword="true" clearable multiple collapse-tags collapse-tags-tooltip> -->
        <!-- <el-select v-model="form.productname" style="width: 240px" allow-create filterable :reserve-keyword="true" clearable>
          <el-option v-for="item in materielList" :key="item.id" :label="item.fnumber" :value="item.id"></el-option>
        </el-select> -->
      </el-form-item>

      <el-form-item label="检验方式" required prop="completecheck">
        <el-select v-model="form.completecheck" placeholder="选择抽检方式">
          <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>

      <el-table :data="form.detailscheck_all" stripe border>
        <el-table-column prop="testitem" label="测试项目" width="180">
          <template #default="scope">
            <el-form-item :prop="'detailscheck_all.' + scope.$index + '.testitem'" :rules="rules.testitem">
              <el-input v-model="scope.row.testitem" name="testitem" clearable />
            </el-form-item>
          </template>
        </el-table-column>

        <el-table-column prop="testmethod" label="测试方法" width="180">
          <template #default="scope">
            <el-form-item :prop="'detailscheck_all.' + scope.$index + '.testmethod'" :rules="rules.testmethod">
              <el-input v-model="scope.row.testmethod" name="testmethod" clearable />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column prop="teststandard" label="测试合格标准" width="200">
          <template #default="scope">
            <el-form-item :prop="'detailscheck_all.' + scope.$index + '.teststandard'" :rules="rules.teststandard">
              <el-input v-model="scope.row.teststandard" name="teststandard" clearable />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column prop="remarks" label="备注" width="180">
          <template #default="scope">
            <el-form-item :prop="'detailscheck_all.' + scope.$index + '.remarks'">
              <el-input v-model="scope.row.remarks" name="remarks" clearable />
            </el-form-item>
          </template>
        </el-table-column>

        <el-table-column prop="teststandard" label="操作" width="180">
          <template #default="scope">
            <el-button type="danger" @click="delHandler(scope.$index)" class="tableBtn">删除</el-button>
            <el-button type="warning" @click="addHandler" v-if="scope.$index == form.detailscheck_all.length - 1" class="tableBtn"> 新增行 </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form>
    <el-dialog v-model="materielShow" title="物料选择" width="80%" style="height: 75vh" :before-close="handleClose">
      <div class="dialogBox"><materialVue :isVue="true" @send-materail="getmaterialHandler"></materialVue></div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="materielShow = false">关闭</el-button>
          <el-button type="primary" @click="confirmmaterialHandler"> 确认 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, computed, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import storage from '/admin/utils/storage'
import http from '/admin/support/http'
import materialVue from '/modules/Base/views/material/index.vue'
const route = useRoute()
const router = useRouter()
const fullscreenLoading = ref(false)
// 物料请求获取id
const getmaterielId = fnumber => {
  fullscreenLoading.value = true
  return new Promise((resolve, reject) => {
    http
      .get(`/base/material?fnumber=${fnumber}`)
      .then(r => {
        let res = r.data.data
        console.log('请求具体物料：', res)
        if (res.length != 0) {
          console.log('请求具体物料id', res[0].id)
          curMaterielId.value = res[0].id
          curMaterielName.value = res[0].fnumber
          // return res[0].id
        } else {
          ElMessage.warning('无对应物料')
        }
        fullscreenLoading.value = false
      })
      .catch(error => {
        reject(error)
        fullscreenLoading.value = false
      })
  })
}

const form = reactive({
  detailscheck_all: [
    {
      testitem: '',
      testmethod: '',
      teststandard: '',
      remarks: '',
    },
  ],
})

// 引入物料组件
const isVue = ref(true)

const ruleFormRef = ref<FormInstance>()

const radioValue = ref('1')
let changeSelect = val => {
  console.log(val)
  form.productname = []
}

const options = ref([
  {
    value: '0',
    label: '抽检',
  },
  {
    value: '1',
    label: '全检',
  },
])

// let materielList = ref([])
let materielList = ref(storage.getItem('materielList'))

console.log('物料编码', materielList.value)
const rules = reactive({
  productname: [{ required: true, trigger: 'confirm', message: '请输入产品名称' }],
  testitem: [{ required: true, message: '不能为空', trigger: 'blur' }],
  testmethod: [{ required: true, message: '不能为空', trigger: 'blur' }],
  teststandard: [{ required: true, message: '不能为空', trigger: 'blur' }],
  completecheck: [{ required: true, message: '不能为空', trigger: 'blur' }],
})

const addHandler = () => {
  let obj = {
    testitem: '',
    testmethod: '',
    teststandard: '',
    remarks: '',
  }
  form.detailscheck_all.push(obj)
}

const delHandler = index => {
  form.detailscheck_all.splice(index, 1)
}

let detailData = ref([])
let materielShow = ref(false)

let choseMatrial = ref([])
// let

// 打开物料选择弹出
const materielopen = () => {
  ElMessage.info('当前只能选一种物料哦')
  materielShow.value = true
}

// 获取子组件返回选中数据
const getmaterialHandler = data => {
  choseMatrial.value = data
}

let curMaterielId = ref('')
let curMaterielName = ref([])

// 确认按钮
const confirmmaterialHandler = () => {
  ElMessage.info('当前只能选一种物料哦')
  console.log('截取当前选中', choseMatrial.value)
  let strID = []
  let strName = []
  choseMatrial.value.forEach(item => {
    strID.push(item.id)
    strName.push(item.fnumber)
  })
  form.productname = strID
  curMaterielName.value = strName
  materielShow.value = false
}

// 页面详情编辑
if (route.query.btnName == '保存修改') {
  detailData.value = JSON.parse(route.query.detailData)
  console.log('路由接收的详情数据', detailData.value)
  getmaterielId(detailData.value.productname)

  let currentCroductname = []

  if (detailData.value.productname != '共用方案') {
    radioValue.value = '1'
    currentCroductname = detailData.value.productname
  } else {
    radioValue.value = '2'
  }

  console.log(currentCroductname)
  // 拿到的当前的物料编码是id数组
  // 暂时改成字符串
  form.productname = currentCroductname
  form.completecheck = String(detailData.value.completecheck)
  detailData.value.detailscheck_all.forEach((item, index) => {
    let obj = {}
    obj.testitem = item.testitem
    obj.testmethod = item.testmethod
    obj.teststandard = item.teststandard
    obj.remarks = item.remarks
    form.detailscheck_all[index] = obj
  })
}

//提交
const submitForm = async (formEl, name) => {
  if (!formEl) return
  fullscreenLoading.value = true
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (radioValue.value != '1') {
        //共用方案
        form.productname = []
      }
      if (name == '保存新增') {
        console.log('新增表单内容：', form)
        http.post('/inspection/inspection', form).then(r => {
          if (r.data.code == '10000') {
            ElMessage({
              message: r.data.message,
              type: 'success',
            })
            ElMessage.success('即将跳转列表页')
            setTimeout(() => {
              goBack()
            }, 1000)
          } else {
            ElMessage({
              message: r.data.message,
              type: 'error',
            })
          }
          fullscreenLoading.value = false
        })
      }

      if (name == '保存修改') {
        if (radioValue.value == '1') {
          console.log('提交修改保存时的物料', form.productname)
          if (form.productname == detailData.value.productname) {
            console.log('没有改动进来了', curMaterielId.value)
            form.productname = [curMaterielId.value]
          }
        }
        console.log('编辑表单内容：', form)
        http.put(`/inspection/inspection/${detailData.value.id}`, form).then(r => {
          if (r.data.code == '10000') {
            ElMessage({
              message: r.data.message,
              type: 'success',
            })
            ElMessage.success('即将跳转列表页')
            setTimeout(() => {
              goBack()
            }, 1000)
          } else {
            ElMessage({
              message: r.data.message,
              type: 'error',
            })
          }
          fullscreenLoading.value = false
        })
      }
    } else {
      ElMessage({
        message: '请输入正确内容格式',
        type: 'warning',
      })
      fullscreenLoading.value = false
    }
  })
}

const goBack = () => {
  router.push('/base/inspection')
}
</script>

<style lang="css">
.rowone {
  margin-bottom: 20px;
  display: flex;
  justify-content: center;
}
.addBtn {
  margin-left: 10px;
}
.btn {
  margin: 10px;
}
.all {
  width: 100%;
}
.el-form-item__content {
  margin-left: 0 !important;
}

.newBtn {
  margin: 30px 20px 0;
}
.tableBtn {
  margin-bottom: 20px;
}
.dialogBox {
  border: 1px solid #000;
  height: 400px;
  overflow: auto;
}
</style>